#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <cbm.h>

#include "Buffers.h"
#include "Trim.h"
#include "Splitter.h"
#include "Drives.h"
#include "Dispatcher.h"

#pragma code-name("RMDIRCODE");
#pragma rodata-name("RMDIRCODE");

unsigned char deleteDirectory(unsigned char driveIndex)
{
	unsigned char r = 0, i = 0;
	int result = 0;
	drive_t *drive = &drives[driveIndex];
	tokenCollection_t *collection = NULL;
	static char buffer[256];
	parsedPath_t *path = NULL;

	strcpy(buffer, buffer3);

	collection = splitString(buffer);

	if(collection->count != 2)
	{
		printf("\nusage: rmdir :directory\n");
		free(collection);
		return 0;
	}

	path = parsePath(1, collection, driveIndex);

	driveIndex = getDrive(path->device);
	if(driveIndex == 0xFF) 
	{
		printf("\nUnknown device.");
		free(collection);
		free(path);
		return 1;
	}
	drive = &drives[driveIndex];


	if(drives[getDrive(path->device)].type == CBM15x1)
	{
		printf("\nDrive does not support directories.");
		free(collection);
		free(path);
		return 1;
	}

	if(strlen(path->file) == 0)
	{
		printf("\nusage: rmdir :directory\n");
		free(collection);
		free(path);
		return 1;
	}

	if(isPattern(path->path))
	{
		printf("\nCannot use pattern in path.");
		free(collection);
		free(path);
		return 1;
	}

	if(isPattern(path->file))
	{
		printf("\nCannot use pattern for target.");
		free(collection);
		free(path);
		return 1;
	}

	if(drive->type == VICE)
	{
		sprintf(buffer3, "cd:%s", path->path);
	}
	else
	{
		sprintf(buffer3, "cd%s", path->path);
	}

	if(executeCommand(drive, buffer3, 0))
	{
		sprintf(buffer3, "rd:%s", path->file);

		r = cbm_open(15, drive->device, 15, buffer3);
		memset(buffer2, 0, sizeof(buffer2));
		result = cbm_read(15, buffer2, sizeof(buffer2));
		cbm_close(15);
		//printf("\n%s", buffer3);

		sscanf(buffer2, "%u,%s", &result, buffer1);

		if(result != 0)
		{
			printf("\n%s", buffer2);
		}

		if(drive->type == VICE)
		{
			sprintf(buffer3, "cd:%s", drive->path);
		}
		else
		{
			sprintf(buffer3, "cd%s", drive->path);
		}

		executeCommand(drive, buffer3, 0);
	}
	else
	{
		printf("\nInvalid path.");
		r = 1;
	}

	free(path);
	free(collection);
	return r;
}
